package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.getImageUrl
import top.kikt.book.util.resolve
import top.kikt.book.util.selectText
import java.nio.charset.Charset

class Qqduu : BaseBookHandler() {

    override fun isSupported(): Boolean {
        return false
    }

    override val host: String
        get() = "www.qqduu.com"

    override fun forceCharset(): Charset = Charset.forName("gbk")

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.selectText("body > div.DivMain > div.DivMainLeft > div > h1")
        val menuUrl = "$url/list/"
        val author =
            document.selectText("body > div.DivMain > div.DivMainLeft > div > div:nth-child(3) > span:nth-child(1)")
        val coverUrl = document.getImageUrl(
            url,
            "body > div.DivMain > div.DivMainLeft > div > div:nth-child(4) > div.DivImage > center > img"
        )
        return BookMetaEntity(name, url, menuUrl, author, coverUrl)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val divs = document.select("#DivTitleList > div > span")

        return divs.mapIndexed { index, it ->
            val name = it.text().trim()
            val url = menuUrl.resolve(it.select("a").attr("href"))
            ChapterMetaEntity(name, index, url, it)
        }
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val document = chapterMetaEntity.toDocument(forceCharset()) ?: return null

        val text = document.selectText("#shenma")

        return ChapterEntity(
            chapterMetaEntity.name,
            chapterMetaEntity.index,
            text,
        )
    }
}